package com.fiberhome.app.network.parse;

import android.text.TextUtils;

import com.google.gson.Gson;
import com.thoughtworks.xstream.XStream;

import java.io.InputStream;

/**
 * Created by Deed on 2018/1/16.
 */

public class Parser {
    private static final Gson GSON = new Gson();
    private static final XStream X_STREAM = new XStream();

    /**
     * @param str String
     * @param cls Class<T>
     * @param <T> T
     * @return T
     */
    public static <T> T parseTo(String str, Class<T> cls) {
        if (!TextUtils.isEmpty(str)) {
            String cleanStr = str.trim();
            if (cleanStr.endsWith(">")) {
                return parseXmlTo(str, cls);
            } else {
                return parseJsonTo(str, cls);
            }
        }
        return null;
    }

    /**
     * @param str String
     * @param cls Class<T>
     * @param <T> T
     * @return T
     */
    public static <T> T parseJsonTo(String str, Class<T> cls) {
        try {
            if (cls != null) {
                return GSON.fromJson(str, cls);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * @param str String
     * @param cls Class<T>
     * @param <T> T
     * @return
     */
    public static <T> T parseXmlTo(String str, Class<T> cls) {
        try {
            XStream xs = new XStream();
            xs.autodetectAnnotations(true);
            xs.processAnnotations(cls);
            xs.alias(cls.getSimpleName(), cls);
            return (T) xs.fromXML(str);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static  <T> T parseTo(InputStream is, Class<T> cls) {
        try {
            XStream xs = new XStream();
            xs.autodetectAnnotations(true);
            xs.processAnnotations(cls);
            xs.alias(cls.getSimpleName(), cls);
            return (T) xs.fromXML(is);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * @param obj Object
     * @return String
     */
    public static String toXml(Object obj) {
        X_STREAM.alias(obj.getClass().getSimpleName(), obj.getClass());
        return X_STREAM.toXML(obj);
    }

    /**
     * @param obj Object
     * @return String
     */
    public static String objToString(Object obj) {
        return GSON.toJson(obj);
    }
}
